package cqie.cn.frame.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-09-11 周六
 * @time 0:43
 * @description
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final String HEADER_TOKEN_KEY = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        String requestURI = request.getRequestURI();
//        log.info("requestURI-->{}", requestURI);
//        if (request.getMethod().equals("OPTIONS")) {
//            response.setStatus(HttpServletResponse.SC_OK);
//            return true;
//        }
//        response.setCharacterEncoding("utf-8");
//        String token = request.getHeader(HEADER_TOKEN_KEY);
//        // 获取请求头
//// 请求头不为空进行解析
//        if (StringUtils.isNotBlank(token)) {
//            Long userId = TokenUtil.verify(token);
//            if (userId == null) {
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录,请登录");
//                return false;
//            }
//            UserVo userInfo = SpringUtils.getBean(ISysUserService.class).getInfoById(userId);
//            if (StringUtils.isBlank(userInfo.getLoginToken())) {
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录,请登录");
//                return false;
//            }
//            UserContext.set(userInfo);
//        } else {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录,请登录");
//        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        UserContext.remove();
    }


    private void initUserContext(String token) {

//        Long userId = TokenUtil.verify(token);
//        UserVo userInfo = SpringUtils.getBean(ISysUserService.class).getInfoById(userId);
//        UserContext.set(userInfo);
    }
}
